package ru.spbau.design.snmp.android.viewer.provider;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import ru.spbau.design.snmp.android.viewer.model.ModelException;
import ru.spbau.design.snmp.android.viewer.model.NetworkSnapshot;
import ru.spbau.design.snmp.android.viewer.model.NetworkSnapshotXMLParser;
import ru.spbau.design.snmp.android.viewer.networking.NetworkClient;

public final class NetworkSnapshotProviderRemote implements INetworkSnapshotProvider {
	
	public NetworkSnapshotProviderRemote(String collectorAddress, int collectorPort) {
		this.collectorAddress = collectorAddress;
		this.collectorPort = collectorPort;
		this.networkClient = new NetworkClient();
	}
	
	@Override
	public NetworkSnapshot getNetworkSnapshot() throws ModelException {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		DocumentBuilder builder;
		Document doc;
		try {
			builder = factory.newDocumentBuilder();
			doc = builder.parse(getInputStream());
			NetworkSnapshotXMLParser snapshotParser = 
				new NetworkSnapshotXMLParser();
			return snapshotParser.parseXML(doc);

		} catch (Exception e) {
			throw new ModelException(e.getMessage());
		}
	}

	private InputStream getInputStream() throws IOException {
		 return this.networkClient.getXML(this.collectorAddress, this.collectorPort);
	}

	private final String collectorAddress;
	private int collectorPort;
	private NetworkClient networkClient;
}